package pers.chy.chyappointmentplatform.Service;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import pers.chy.chyappointmentplatform.Controller.CallNumberController;
import pers.chy.chyappointmentplatform.Mapper.HisMapper.Yjyy_PdjhMapper;
import pers.chy.chyappointmentplatform.Model.Yjyy_PdjhDTO;
import pers.chy.chyappointmentplatform.Utils.ChyException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AppointService {


    @Autowired
    private Yjyy_PdjhMapper yjyy_pdjhMapper;

    /**
     * 取号
     *
     * @param params
     * @return
     * @throws Exception
     */
    public Yjyy_PdjhDTO doTakeQuequeNumber(Map params, String czrygh, String czryxm) throws Exception {


        try {
            Date now = new Date();
            Logger log = LoggerFactory.getLogger(AppointService.class);

            // 获取此队列的当日最大的排队号码
            Yjyy_PdjhDTO todayMaxRecord = yjyy_pdjhMapper.selectMaxRecordToday(Long.parseLong(params.get("dlxh").toString()));

            // 数据准备
            Yjyy_PdjhDTO entity = new Yjyy_PdjhDTO();
            entity.setPdhm(todayMaxRecord == null ? 1 : todayMaxRecord.getPdhm() + 1);
            entity.setBrxm(params.get("brxm").toString());
            entity.setSfzh(params.get("sfzh").toString());
            entity.setJzlx(1);  // 就诊类型 暂时都设为1（门诊）
            entity.setYysj(now);
            entity.setYwlx(Integer.parseInt(params.get("ywlx").toString()));
            entity.setJjbz(0);  // 直接取号的，默认紧急标志=0
            entity.setQdbz(1);  // 直接取号的，默认签到标志=1
            entity.setDlxh(Integer.parseInt(params.get("dlxh").toString()));
            entity.setDlmc(params.get("dlmc").toString());
            entity.setYyrygh(czrygh);
            entity.setYyryxm(czryxm);
            if (params.get("brnl") != null) {
                entity.setBrnl(params.get("brnl").toString());
            }
            if (params.get("brxb") != null) {
                entity.setBrxb(params.get("brxb").toString());
            }
            if (params.get("jtdz") != null) {
                entity.setJtdz(params.get("jtdz").toString());
            }
            if (params.get("bzxx") != null) {
                entity.setBzxx(params.get("bzxx").toString());
            }

            // 插入排队取号表 (循环操作，防止并发)
            boolean isContinue = true;
            int count = 0;
            while (isContinue) {
                try {
                    yjyy_pdjhMapper.insert(entity);
                    isContinue=false;
                } catch (Exception ex) {
                    // 如果是违反唯一约束（pdhm、dlxh、qhrq不能同时相同），尝试排队号+1
                    if (ex instanceof org.springframework.dao.DuplicateKeyException) {

                        // 违反唯一索引次数+1
                        count++;

                        //
                        log.error("[错误] 取号时违反唯一索引，当前第{}次",count);

                        //
                        entity.setPdhm(entity.getPdhm() + 1);

                        // 最多尝试30次
                        if (count < 30) {
                            isContinue = true;
                        }else{
                            isContinue = false;
                            break;
                        }
                    } else {
                        isContinue = false;
                        throw ex;
                    }
                }
            }


            //
            Yjyy_PdjhDTO ret = new Yjyy_PdjhDTO();
            ret.setPdhm(entity.getPdhm());
            ret.setBrxm(entity.getBrxm());
            ret.setSfzh(entity.getSfzh());
            ret.setYysj(entity.getYysj());
            return ret;
        } catch (Exception ex) {
            throw ex;
        }

    }
}
